// import { loginApi } from '../../../apis/modules/login'
import { HOME_URL } from "../../../constants";
import { setToken } from '../../../store/modules/global'
import { CloseCircleOutlined, LockOutlined, UserOutlined } from '@ant-design/icons'
import { Button, Form, Input, message } from 'antd'
import { useState } from 'react'
import { useDispatch } from 'react-redux'
import { useNavigate } from "react-router-dom";
import { getMenuList } from '../../../apis/modules/login'
import { setMenuList } from '../../../store/modules/menu'
import { setAuthRouter } from '../../../store/modules/auth'
import { handleRouter } from '../../../utils/utils'
import { useTranslation } from "react-i18next";

const LoginForm = () => {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState<boolean>(false)
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const { t } = useTranslation();

  const onFinish = async () => {
    try {
      setLoading(true)
      // 1.执行登录接口
      // const { code, data } = await loginApi(loginForm);
      dispatch(setToken("11111111"));

      // 2.添加动态路由
      const { data } = await getMenuList();

      dispatch(setMenuList(data));
      // 把路由菜单处理成一维数组，存储到 redux 中，做菜单权限判断
      dispatch(setAuthRouter(handleRouter(data)));

      // 3.清空 tabs、keepAlive 数据
      // 4.跳转到首页
      navigate(HOME_URL);
      message.success(t('login.success'))
    } finally {
      setLoading(false)
    }
  }

  return (
    <Form
      form={form}
      name="login-form"
      size='large'
      labelCol={{ span: 5 }}
      autoComplete='off'
      onFinish={onFinish}
    >
      <Form.Item
        name="username"
        rules={[{ required: true, message: "请输入用户名！" }]}
      >
        <Input prefix={<UserOutlined />} placeholder="用户名：admin" />
      </Form.Item>
      <Form.Item name="password" rules={[{ required: true, message: "请输入密码！" }]}>
        <Input.Password placeholder="密码：123456" prefix={<LockOutlined />} />
      </Form.Item>
      <Form.Item className="login-btn">
        <Button
          onClick={() => {
            form.resetFields()
          }}
          icon={<CloseCircleOutlined />}
          >
            {t('login.reset')}
          </Button>
          <Button type="primary" htmlType="submit" loading={loading} icon={<UserOutlined />}>
            {t('login.confirm')}
          </Button>
      </Form.Item>
    </Form>
  )
}

export default LoginForm
